import React, { useState } from 'react';
import styles from './TicTacToe.module.css';

const TicTacToe = () => {
    // 棋盘状态
    const [squares, setSquares] = useState(Array(9).fill(null));
    // 下一步是否是 X
    const [isXNext, setIsXNext] = useState(true);

    // 计算获胜者
    const calculateWinner = (squares) => {
        const lines = [
            [0, 1, 2], // 横向
            [3, 4, 5],
            [6, 7, 8],
            [0, 3, 6], // 纵向
            [1, 4, 7],
            [2, 5, 8],
            [0, 4, 8], // 对角线
            [2, 4, 6],
        ];

        for (let i = 0; i < lines.length; i++) {
            const [a, b, c] = lines[i];
            if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
                return squares[a];
            }
        }
        return null;
    };

    // 处理点击方格
    const handleClick = (i) => {
        if (calculateWinner(squares) || squares[i]) {
            return;
        }
        const newSquares = squares.slice();
        newSquares[i] = isXNext ? 'X' : 'O';
        setSquares(newSquares);
        setIsXNext(!isXNext);
    };

    // 重置游戏
    const resetGame = () => {
        setSquares(Array(9).fill(null));
        setIsXNext(true);
    };

    const winner = calculateWinner(squares);
    const isDraw = !winner && squares.every(square => square !== null);
    let status;
    if (winner) {
        status = `获胜者: ${winner}`;
    } else if (isDraw) {
        status = '平局！';
    } else {
        status = `下一步: ${isXNext ? 'X' : 'O'}`;
    }

    return (
        <div className={styles.game}>
            <div className={styles.status}>{status}</div>
            <div className={styles.board}>
                {squares.map((square, i) => (
                    <button
                        key={i}
                        className={styles.square}
                        onClick={() => handleClick(i)}
                    >
                        {square}
                    </button>
                ))}
            </div>
            <button 
                className={styles.resetButton}
                onClick={resetGame}
            >
                重新开始
            </button>
        </div>
    );
};

export default TicTacToe;